﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Data;
using SilverlightTetris_M10CDE.Web.HiScore;

namespace SilverlightTetris_M10CDE.Web
{
    public class ScoreFactory
    {
        /// <summary>
        /// empty constructor
        /// </summary>
        public ScoreFactory(){
        }


          /// <summary>
          /// utilises the LINQ to XML module 'XElement'
          /// decrypt the string parameters using a predefined key
          /// create a string called FileLocation and put location of XML file in it
          /// create a XElement called xml and load the contents of the FileLocation XML file
          /// add our new element with the contents of the methods parameters
          /// save new xml file to filelocation XML file
          /// </summary>
          /// <param name="name"></param>
          /// <param name="score"></param>
          /// <param name="levelReached"></param>
          /// <param name="timeTaken"></param>
          /// <param name="date"></param>
        public static void addScore(String name, String score, String lines, String levelReached, String timeTaken, String date)
        {
            name =          Encryption.Decrypt(name,         "tetris");
            score =         Encryption.Decrypt(score,        "tetris");
            lines =         Encryption.Decrypt(lines,        "tetris");
            levelReached =  Encryption.Decrypt(levelReached, "tetris");
            timeTaken =     Encryption.Decrypt(timeTaken,    "tetris");
            date =          Encryption.Decrypt(date,         "tetris");

            if (levelReached == "")            //short IF ELSE to write a 0 as the LevelReached   
            {                                  //vars value instead of leaving it blank
                levelReached = "0";
            }

            String fileLocation = HttpContext.Current.Server.MapPath("HiScore/scores.xml");   //set the file Location var to be the location of the xml file

            if (!File.Exists(fileLocation))                         // if the file does not exist, create it and add in the root tag "Scores"
            {                                           
                XmlTextWriter myWriter = new XmlTextWriter(fileLocation, null);
                myWriter.WriteStartElement("Scores");
                myWriter.WriteEndElement();
                myWriter.Close();
            }

            XElement xml = XElement.Load(fileLocation);           //create a single record of data that starts with <Record>, contains all necessary data inside of those tags
            
            xml.Add(new XElement("Record",
                        new XElement("Name", name),
                        new XElement("Score", score),
                        new XElement("Lines", lines),
                        new XElement("LevelReached", levelReached),
                        new XElement("TimeTaken", timeTaken),
                        new XElement("Date", date)));

            xml.Save(fileLocation);                               //save the XML with new score data to the decryptedXMLString variable, overwriting old contents
            
        }

        /// <summary>
        /// reads xml data from the XML file score.xml and outputs a Score container object.
        /// </summary>
        /// <returns>returns the contents of the XML file in the form of a List data structure containing Score objects</returns>
        public static List<Score> getScoreTable()
        {
            String xmlPath = HttpContext.Current.Server.MapPath("HiScore/scores.xml");  //as it runs as a web service it changes directory. We need to use a mapPath  
            XDocument myDoc = XDocument.Load(xmlPath);                                  // method to reroute to the REAL location of the XML file
            var scores = from record in myDoc.Descendants("Record")                  // use a generic var to hold an empty record from the XML file
                         select new
                         {
                             name = record.Element("Name").Value,
                             score = record.Element("Score").Value,
                             lines = record.Element("Lines").Value,
                             levelReached = record.Element("LevelReached").Value,
                             timeTaken = record.Element("TimeTaken").Value,
                             date = record.Element("Date").Value,
                         };

            List<Score> scoreList = new List<Score>();      //setup a list for Score objects, ready to be populated

            foreach (var record in scores)  //loop over all records in the XML file and turn them into an object
            {
                Score myScore = new Score(record.name, record.score, record.lines, 
                                          record.levelReached, record.timeTaken, record.date);  // create an object with values of XML record
                scoreList.Add(myScore); //add object to a list of objects, ready to be returned
            }
            /*                                                                  //old string sorting code, redundant now
                scoreList.Sort();    //sort list by score size, biggest first   //
                foreach (Score x in scoreList)                                  //
                {                                                               //
                    formattedOutputString += x.toString();                      //
                }   
            */
            return scoreList;
        }

    }
    
}